<script setup lang="tsx">
import {
  Attachments,
  type AttachmentsProps,
  Bubble,
  type BubbleListProps,
  Conversations,
  type ConversationsProps,
  Prompts,
  type PromptsProps,
  Sender,
  Welcome
} from 'ant-design-x-vue';
import {
  CloudUploadOutlined,
  CommentOutlined,
  EllipsisOutlined,
  FireOutlined,
  HeartOutlined,
  PaperClipOutlined,
  PlusOutlined,
  ReadOutlined,
  ShareAltOutlined,
  SmileOutlined,
} from '@ant-design/icons-vue';
import { Badge, Button, Space, theme, message, Alert } from 'ant-design-vue';
import { computed, ref, watch, onMounted, onUnmounted, defineComponent, type VNode } from 'vue';
import { v4 as uuidv4 } from 'uuid';
import { sseClient, SSEConnectionStatus } from '../../api/sseChat';
import type { SSEReplyEvent, ReferenceEvent } from '../../types/sse';
import { checkSSESupport, checkSSEConnection, logDetailedError, debugLog } from '../../utils/debugHelper';

const name = 'ChatPanel';

// 等待函数
const sleep = () => new Promise((resolve) => setTimeout(resolve, 500));

// 渲染标题
const renderTitle = (icon: VNode, title: string) => (
  <Space align="start">
    {icon}
    <span>{title}</span>
  </Space>
);

// 热门话题选项
const placeholderPromptsItems: PromptsProps['items'] = [
  {
    key: '1',
    label: renderTitle(<FireOutlined style={{ color: '#FF4D4F' }} />, '热门话题'),
    description: '您对哪些话题感兴趣？',
    children: [
      {
        key: '1-1',
        description: 'X有什么新功能？',
      },
      {
        key: '1-2',
        description: '什么是AGI？',
      },
      {
        key: '1-3',
        description: '在哪里查看文档？',
      },
    ],
  },
  {
    key: '2',
    label: renderTitle(<ReadOutlined style={{ color: '#1890FF' }} />, '设计指南'),
    description: '如何设计一个好产品？',
    children: [
      {
        key: '2-1',
        icon: <HeartOutlined />,
        description: '了解产品',
      },
      {
        key: '2-2',
        icon: <SmileOutlined />,
        description: '设置AI角色',
      },
      {
        key: '2-3',
        icon: <CommentOutlined />,
        description: '表达感受',
      },
    ],
  },
];

// 发送框提示词
const senderPromptsItems: PromptsProps['items'] = [
  {
    key: '1',
    description: '热门话题',
    icon: <FireOutlined style={{ color: '#FF4D4F' }} />,
  },
  {
    key: '2',
    description: '设计指南',
    icon: <ReadOutlined style={{ color: '#1890FF' }} />,
  },
];

// 对话角色设置
const roles: BubbleListProps['roles'] = {
  ai: {
    placement: 'start',
    typing: { step: 5, interval: 20 },
    styles: {
      content: {
        borderRadius: '16px',
      },
    },
  },
  local: {
    placement: 'end',
    variant: 'shadow',
  },
};

// ==================== 样式 ====================
const { token } = theme.useToken();
const styles = computed(() => {
  return {
    layout: {
      width: '100%',
      'min-width': '1280px',
      height: '674px',
      'border-radius': `${token.value.borderRadius}px`,
      display: 'flex',
      background: `${token.value.colorBgContainer}`,
      'font-family': `AlibabaPuHuiTi, ${token.value.fontFamily}, sans-serif`,
    },
    menu: {
      background: `${token.value.colorBgLayout}80`,
      width: '280px',
      height: '100%',
      display: 'flex',
      'flex-direction': 'column',
    },
    conversations: {
      padding: '0 12px',
      flex: 1,
      'overflow-y': 'auto',
    },
    chat: {
      height: '100%',
      width: '100%',
      'max-width': '700px',
      margin: '0 auto',
      'box-sizing': 'border-box',
      display: 'flex',
      'flex-direction': 'column',
      padding: `${token.value.paddingLG}px`,
      gap: '16px',
    },
    messages: {
      flex: 1,
      'overflow-y': 'auto',
    },
    placeholder: {
      'padding-top': '32px',
    },
    sender: {
      'box-shadow': token.value.boxShadow,
    },
    logo: {
      display: 'flex',
      height: '72px',
      'align-items': 'center',
      'justify-content': 'start',
      padding: '0 24px',
      'box-sizing': 'border-box',
    },
    'logo-img': {
      width: '24px',
      height: '24px',
      display: 'inline-block',
    },
    'logo-span': {
      display: 'inline-block',
      margin: '0 8px',
      'font-weight': 'bold',
      color: token.value.colorText,
      'font-size': '16px',
    },
    addBtn: {
      background: '#1677ff0f',
      border: '1px solid #1677ff34',
      width: 'calc(100% - 24px)',
      margin: '0 12px 24px 12px',
    }
  } as const
});

// 消息类型
interface ChatMessage {
  id: string;
  content: string;
  role: 'user' | 'assistant';
  status?: 'loading';
  references?: ReferenceEvent['references'];
  is_strem?: boolean;
}

// ==================== 状态 ====================
const headerOpen = ref(false);
const content = ref('');
const conversationsItems = ref([
  {
    key: '0',
    label: '新会话',
  },
]);
const activeKey = ref('0');
const attachedFiles = ref<AttachmentsProps['items']>([]);
const loading = ref(false);
const messages = ref<ChatMessage[]>([]);
const currentSessionId = ref('test');
const visitorId = ref('test');
const currentReferences = ref<ReferenceEvent['references']>([]);
const connectionError = ref<string | null>(null);

// ==================== SSE事件处理 ====================
onMounted(async () => {
  // 检查SSE支持情况
  if (!checkSSESupport()) {
    message.error('您的浏览器不支持SSE，请使用Chrome、Firefox或Edge浏览器');
    connectionError.value = '浏览器不支持SSE';
    return;
  }

  // 检查SSE连接
  try {
    const sseUrl = import.meta.env.VITE_SSE_URL || 'https://wss.lke.cloud.tencent.com/v1/qbot/chat/sse';
    const connectionStatus = await checkSSEConnection(sseUrl);
    
    if (connectionStatus.connectionErrorMessage) {
      connectionError.value = connectionStatus.connectionErrorMessage;
      message.warning(`SSE连接检查：${connectionStatus.connectionErrorMessage}`);
    }
    
    if (connectionStatus.corsErrorMessage) {
      message.warning(`CORS检查：${connectionStatus.corsErrorMessage}`);
    }
    
    debugLog('SSE连接检查结果', connectionStatus);
  } catch (error) {
    logDetailedError(error, 'SSE连接检查');
    message.error('SSE连接检查失败');
  }

  // 设置SSE回调
  sseClient.setCallbacks({
    onReply: (event) => {
      debugLog('SSE Reply:', event);
      handleReplyEvent(event);
    },
    onReference: (event) => {
      debugLog('SSE Reference:', event);
      handleReferenceEvent(event);
    },
    onTokenStat: (event) => {
      debugLog('SSE Token Stat:', event);
    },
    onThought: (event) => {
      debugLog('SSE Thought:', event);
      handleThoughtEvent(event);
    },
    onError: (error) => {
      logDetailedError(error, 'SSE Error');
      connectionError.value = error.message;
      message.error(`错误: ${error.message}`);
      loading.value = false;
    },
    onConnectionStatusChange: (status) => {
      debugLog('SSE Connection Status:', status);
      
      if (status === SSEConnectionStatus.OPEN) {
        connectionError.value = null;
      } else if (status === SSEConnectionStatus.ERROR) {
        connectionError.value = '连接错误';
      } else if (status === SSEConnectionStatus.CLOSED) {
        loading.value = false;
      }
    },
  });
});

onUnmounted(() => {
  sseClient.close();
});

// 处理回复事件
const handleReplyEvent = (event: SSEReplyEvent) => {
    const existingMessageIndex = messages.value.findIndex(
    (msg: any) => (msg.role === 'assistant' && msg.status === 'loading') || msg.is_strem == true
  );

  if (existingMessageIndex !== -1) {
    
    
    // // 如果是最终回复，移除loading状态
    
    messages.value[existingMessageIndex].status = undefined;
    messages.value[existingMessageIndex].is_strem = true;

    // 更新现有消息并流式显示
    messages.value[existingMessageIndex].content = event.content;

    if (event.is_final) {
      messages.value[existingMessageIndex].status = undefined;
      messages.value[existingMessageIndex].is_strem = false;
    }
    // 如果是最终回复，移除loading状态
    // if (isComplete) {
    //   messages.value[existingMessageIndex].status = undefined;
    //     messages.value[existingMessageIndex].is_strem = false;
    // }
  } 
//   else if (!event.is_from_self) {
//     // 添加助手消息
//     // messages.value.push({
//     //   id: event.record_id,
//     //   content: event.content,
//     //   role: 'assistant',
//     //   status: event.is_final ? undefined : 'loading'
//     // });
//   }
};

// 处理参考来源事件
const handleReferenceEvent = (event: ReferenceEvent) => {
  currentReferences.value = event.references;
  
  // 为相应的消息添加引用
  const messageIndex = messages.value.findIndex((msg: ChatMessage) => 
    msg.role === 'assistant' && msg.id === event.record_id
  );
  
  if (messageIndex !== -1) {
    messages.value[messageIndex].references = event.references;
  }
};

// 处理思考事件
const handleThoughtEvent = (event: any) => {
  // 检查是否有思考内容
  if (!event.procedures || event.procedures.length === 0) {
    return;
  }

  // 获取第一个思考过程
  const procedure = event.procedures[0];
  
  // 确保有内容
  if (!procedure.debugging || !procedure.debugging.content) {
    return;
  }
  
  const content = procedure.debugging.content;
  const isComplete = procedure.status === 'success';
  
  const existingMessageIndex = messages.value.findIndex(
    (msg: any) => (msg.role === 'assistant' && msg.status === 'loading') || msg.is_strem == true
  );

//   if (existingMessageIndex !== -1) {
//     console.log(content)
//     console.log(messages.value)
//     // 更新现有消息，流式显示
//     messages.value[existingMessageIndex].status = undefined;
//     messages.value[existingMessageIndex].is_strem = true;

//     messages.value[existingMessageIndex].content = content;
    
//     // 如果是最终回复，移除loading状态
//     if (isComplete) {
//       messages.value[existingMessageIndex].status = undefined;
//         messages.value[existingMessageIndex].is_strem = false;
//     }
//   }
};

// ==================== 事件处理 ====================
const onSubmit = (nextContent: string) => {
  if (!nextContent) return;
  
  // 检查SSE支持和连接状态
  if (!checkSSESupport()) {
    message.error('您的浏览器不支持SSE，请使用Chrome、Firefox或Edge浏览器');
    return;
  }
  
  if (connectionError.value) {
    message.warning(`连接存在正常对话：${connectionError.value}`);
  }
  
  // 添加用户消息
  messages.value.push({
    id: uuidv4(),
    content: nextContent,
    role: 'user'
  });
  
  // 添加一个带loading状态的助手消息
  messages.value.push({
    id: uuidv4(),
    content: '',
    role: 'assistant',
    status: 'loading'
  });
  
  // 清空输入框
  content.value = '';
  
  // 设置loading状态
  loading.value = true;
  
  try {
    // 发送消息到SSE服务
    sseClient.sendChatMessage(
      nextContent,
      currentSessionId.value,
      visitorId.value
    );
  } catch (error) {
    logDetailedError(error, '发送消息');
    message.error('消息发送失败，请稍后重试');
    
    // 移除加载状态的消息
    messages.value = messages.value.filter(msg => msg.status !== 'loading');
    loading.value = false;
  }
};

const onPromptsItemClick: PromptsProps['onItemClick'] = (info: any) => {
  if (info?.data?.description) {
    onSubmit(info.data.description as string);
  }
};

const onAddConversation = () => {
  // 创建新会话
  const newKey = `${conversationsItems.value.length}`;
  conversationsItems.value = [
    ...conversationsItems.value,
    {
      key: newKey,
      label: `新会话 ${conversationsItems.value.length}`,
    },
  ];
  activeKey.value = newKey;
  
  // 重置会话状态
  currentSessionId.value = uuidv4();
  messages.value = [];
  currentReferences.value = [];
};

const onConversationClick: ConversationsProps['onActiveChange'] = (key: string) => {
  if (key !== activeKey.value) {
    activeKey.value = key;
    
    // 切换会话时重置状态
    if (loading.value) {
      sseClient.close();
      loading.value = false;
    }
    
    // 重置消息
    messages.value = [];
    currentReferences.value = [];
    
    // 生成新的会话ID
    currentSessionId.value = uuidv4();
  }
};

const handleFileChange: AttachmentsProps['onChange'] = (info: any) =>
  attachedFiles.value = info.fileList;

// ==================== 渲染节点 ====================
const placeholderNode = computed(() => (
  <Space direction="vertical" size={16} style={styles.value.placeholder}>
    <Welcome
      variant="borderless"
      icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
      title="您好，欢迎使用私有化知识库CHATAI"
      description={connectionError.value ? `当前连接状态异常: ${connectionError.value}` : "智能助手将为您提供专业的回答与服务"}
      extra={
        <Space>
          <Button icon={<ShareAltOutlined />} />
          <Button 
            icon={<EllipsisOutlined />} 
            onClick={() => {
              // 重新检查连接
              checkSSEConnection(import.meta.env.VITE_SSE_URL || 'https://wss.lke.cloud.tencent.com/v1/qbot/chat/sse')
                .then(result => {
                  if (result.connectionErrorMessage) {
                    connectionError.value = result.connectionErrorMessage;
                    message.warning(`SSE连接检查：${result.connectionErrorMessage}`);
                  } else {
                    connectionError.value = null;
                    message.success('SSE连接正常');
                  }
                })
                .catch(error => {
                  logDetailedError(error, 'SSE连接检查');
                  message.error('SSE连接检查失败');
                });
            }}
          />
        </Space>
      }
    />
    {connectionError.value ? (
      <Alert
        message="连接问题"
        description={`检测到SSE连接问题: ${connectionError.value}。请刷新页面或检查网络连接。`}
        type="warning"
        showIcon
      />
    ) : (
      <Prompts
        title="您想了解什么？"
        items={placeholderPromptsItems}
        styles={{
          list: {
            width: '100%',
          },
          item: {
            flex: 1,
          },
        }}
        onItemClick={onPromptsItemClick}
      />
    )}
  </Space>
));

const messageItems = computed<BubbleListProps['items']>(() => 
  messages.value.map(({ id, content, role, status, references }) => {
    // 处理引用标记的情况
    let processedContent = content;
    
    // 构建气泡项
    const item: any = {
      key: id,
      loading: status === 'loading',
      role: role === 'user' ? 'local' : 'ai',
      content: processedContent,
    };
    
    // 添加引用来源菜单
    if (references && references.length > 0) {
      item.menu = references.map((ref, index) => ({
        key: `${index}`,
        label: ref.name,
        onClick: () => {
          if (ref.url) {
            window.open(ref.url, '_blank');
          }
        }
      }));
    }
    
    return item;
  })
);

const attachmentsNode = computed(() => (
  <Badge dot={attachedFiles.value.length > 0 && !headerOpen.value}>
    <Button type="text" icon={<PaperClipOutlined />} onClick={() => headerOpen.value = !headerOpen.value} />
  </Badge>
));

const senderHeader = computed(() => (
  <Sender.Header
    title="附件"
    open={headerOpen.value}
    onOpenChange={(open: boolean) => headerOpen.value = open}
    styles={{
      content: {
        padding: 0,
      },
    }}
  >
    <Attachments
      beforeUpload={() => false}
      items={attachedFiles.value}
      onChange={handleFileChange}
      placeholder={(type: string) =>
        type === 'drop'
          ? { title: '拖拽文件到此处' }
          : {
            icon: <CloudUploadOutlined />,
            title: '上传文件',
            description: '点击或拖拽文件到此区域上传',
          }
      }
    />
  </Sender.Header>
));

const logoNode = computed(() => (
  <div style={styles.value.logo}>
    <span style={styles.value['logo-span']}>私有化知识库CHATAI-DEMO</span>
  </div>
));

defineRender(() => {
  return (
    <div style={styles.value.layout}>
        <div style={styles.value.menu}>
          {/* 🌟 Logo */}
          {logoNode.value}
          {/* 🌟 添加会话 */}
          <Button
            onClick={onAddConversation}
            type="link"
            style={styles.value.addBtn}
            icon={<PlusOutlined />}
          >
            新建会话
          </Button>
          {/* 🌟 会话管理 */}
          <Conversations
            items={conversationsItems.value}
            style={styles.value.conversations}
            activeKey={activeKey.value}
            onActiveChange={onConversationClick}
          />
        </div>
        <div style={styles.value.chat}>
          {/* 🌟 消息列表 */}
          <Bubble.List
            items={messageItems.value.length > 0 ? messageItems.value : [{ content: placeholderNode.value, variant: 'borderless' }]}
            roles={roles}
            style={styles.value.messages}
          />
          {/* 🌟 提示词 */}
          <Prompts style={{ color: token.value.colorText }} items={senderPromptsItems} onItemClick={onPromptsItemClick} />
          {/* 🌟 输入框 */}
          <Sender
            value={content.value}
            header={senderHeader.value}
            onSubmit={onSubmit}
            onChange={(value: string) => content.value = value}
            prefix={attachmentsNode.value}
            loading={loading.value}
            style={styles.value.sender}
          />
        </div>
      </div>
  )
});
</script>